package _56_删除链表中的重复结点;

import java.util.HashMap;

/*
在一个排序的链表中，存在重复的结点，请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。 例如，链表1->2->3->3->4->4->5 处理后为 1->2->5
 */
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null) return null;
        HashMap<Integer, Integer> map = new HashMap<>();
        ListNode p = pHead;
        while (p != null) {
            map.put(p.val, map.getOrDefault(p.val, 0) + 1);
            p = p.next;
        }
        p = pHead;
        ListNode pre = null;
        while (p != null) {
            int count = map.get(p.val);
            if (count > 1) {
                if (pre == null) {
                    pHead = pHead.next;
                    p=pHead;
                } else {
                    pre.next = p.next;
                    p = p.next;
                }
            } else {
                pre = p;
                p = p.next;
            }


        }
        return pHead;
    }
}
